const http = require('http'),
      url = require('url'),
      queryString = require('querystring'),
      request = require('request');



async function TransRequest(method='get',url,data){
    return new Promise((resolve,reject)=>{
        if(method.toLowerCase()=="post"){
            let tmpStr="";
            if(typeof data == "object"){
                for( k in data){
                    tmpStr+= `${k}=${data[k]}&`
                }
                tmpStr=tmpStr.slice(0,-1);
            }
            if(typeof url == "string"){
                url=/\?$/.test(url)?url+tmpStr:url+"?"+tmpStr;
            }
            console.log(url)
        }
        request({
            method:"GET",
            uri:url ,
            headers: {
                "Host":"ac.qq.com",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
                }
        },
        (err,res)=>{
            if(err){
                reject(err);
                return
            }
            resolve(res.request.req.res.body);
        })
    })
}

async function getData(req){
    return new Promise((resolve,reject)=>{
        try {
            let tmpStr="";
            req.on("data",async (chunk)=>{
                tmpStr+=chunk;
            });
            req.on("end",async ()=>{
                resolve(queryString(tmpStr))
            })
        } catch (error) {
            reject(error)
        }
        
    })
}


http.createServer(async (req,res)=>{
    try {
        let location =url.parse(req.url);
        // console.log(location.path);
        if(location.path=="/favicon.ico"){
            res.end()
            return
        }
        if(true){
            // let apiUrl = location.path.match(/(ajax)(\W|\w)*/)[0];
            // let baseUrl="http://m.maoyan.com/";
            // let turl = baseUrl+apiUrl;

            let TransRes= await TransRequest("get","http://ac.qq.com/ComicView/index/id/530876/cid/2");
            // console.log(TransRes)    
            res.setHeader("Content-Type","text/html;charset=utf-8");
            res.setHeader("Acess-Control-Allow-Origin","*");
            
            // console.log(TransRes.toString().match(/window.nonce.*;/)[0]);
            res.end(TransRes+"<script>console.log(window)</script>");
            return
        }
        res.end("hi");
    } catch (error) {
        console.log(error)
        res.end("{msg:error}")
    }
}).listen("8888");

console.log(`listening: //localhost:8888`)
